<template>
  <div>
    <!-- 搜索部分 -->
    <div class="tableSearch">
      <el-form size="mini" :model="ruleForm" :rules="rules" ref="ruleForm">
        <el-form-item label="日期：" label-width="80px" prop="date">
          <el-date-picker
            v-model="ruleForm.date"
            type="date"
            format="yyyy年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            placeholder="请选择"
            :picker-options="pickerOptions"
            style="width:180px;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="商品分类：" label-width="120px">
          <el-cascader
            expand-trigger="hover"
            change-on-select
            v-model="ruleForm.primaryClassifyId"
            :options="options"
            placeholder="请选择"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="门店：" label-width="100px" prop="shopId">
          <el-select v-model="ruleForm.shopId" placeholder="请选择">
            <el-option
              v-for="item in storeArr"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="毛利额：" label-width="100px">
          <el-form-item label label-width="0" prop="startProfit">
            <el-input v-model="ruleForm.startProfit" style="width:100px;"></el-input>
          </el-form-item>
          <el-form-item label label-width="0">&nbsp;-&nbsp;</el-form-item>
          <el-form-item label label-width="0" prop="endProfit">
            <el-input v-model="ruleForm.endProfit" style="width:100px;"></el-input>
          </el-form-item>
        </el-form-item>
        <el-form-item label label-width="35px">
          <el-button type="primary" @click="submitForm('ruleForm')">查询</el-button>
        </el-form-item>
        <el-form-item label label-width="15px">
          <el-button type="primary" v-if="setRole('导出')" @click="handleOutput()">导出</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 门店汇总数据-表格 -->
    <el-table :data="tableData">
      <el-table-column prop="goodsName" label="商品名称" align="center"></el-table-column>
      <el-table-column prop="primaryClassifyName" label="商品分类" align="center"></el-table-column>
      <el-table-column prop="goodsAmount" label="商品实收金额" align="center"></el-table-column>
      <el-table-column prop="latestPriceAmount" label="库存成本" align="center"></el-table-column>
      <el-table-column prop="profit" label="毛利额" align="center"></el-table-column>
    </el-table>
    <page-unit :pageData="pageData" :func="_listGoodsProfit"></page-unit>
  </div>
</template>

<script>
import { mapState } from "vuex";
import pageUnit from "@/components/Page";
import u from "@/util";
import {
  listGoodsProfit,
  getGoodsClassifyTreeList,
  selectBaseShopPageList,
  goodsProfitExport // 导出
} from "@/api/index.js";
const fileDownload = require("js-file-download");

export default {
  computed: mapState(["sub", "merchantId", "power", "isShop", "linkName"]),
  components: { pageUnit },
  data() {
    // 验证输入格式 ！！！！
    var priceValid = (rule, value, callback) => {
      if (!value) {
        if (
          this.ruleForm.startProfit !== "" ||
          this.ruleForm.endProfit !== ""
        ) {
          return callback(new Error("输入不能为空"));
        }
        return callback();
      }
      setTimeout(() => {
        let reg = /(^[1-9][0-9]{0,6}(\.[0-9]{1,2})?$)|(^\-[1-9]{1}[0-9]{0,6}(\.[0-9]{1,2})?$)|(0)/;
        if (!reg.test(value)) {
          callback(new Error("输入格式不正确"));
        } else {
          callback();
        }
      }, 1000);
    };
    // 验证比priceMax小等 !!!
    var validatePriceMin = (rule, value, callback) => {
      if (!value) {
        return callback();
      } else {
        if (this.ruleForm.endProfit !== "") {
          if (
            Number(this.ruleForm.startProfit) > Number(this.ruleForm.endProfit)
          ) {
            callback(new Error("不能大！！！"));
          } else {
            callback();
          }
        }
      }
    };
    // 验证比priceMin大 !!!
    var validatePriceMax = (rule, value, callback) => {
      if (!value) {
        return callback();
      } else {
        if (this.ruleForm.startProfit !== "") {
          if (
            Number(this.ruleForm.endProfit) < Number(this.ruleForm.startProfit)
          ) {
            callback(new Error("不能小！！！"));
          } else {
            callback();
          }
        }
      }
    };
    return {
      ruleForm: {
        date: "", // 日期
        primaryClassifyId: [""], // 商品分类id
        shopId: "", // 门店id
        startProfit: "", // 毛利额
        endProfit: "" // 毛利额
      },
      options: [], // 商品分类数组
      storeArr: [], // 门店数组
      tableData: [], // 筛选出商品的数组
      exportData: {}, // 导出数据条件
      pageData: {
        pageSize: 10,
        currentPage: 1,
        totalItems: 0,
        pageSizeArr: [5, 10, 20]
      },
      rules: {
        shopId: [
          { required: true, message: "请选择一个门店", trigger: "change" }
        ],
        date: [{ required: true, message: "请选择日期", trigger: "change" }],
        startProfit: [
          { required: false,validator: priceValid, trigger: "change" },
          { validator: validatePriceMin, trigger: "change" }
        ],
        endProfit: [
          { required: false,validator: priceValid, trigger: "change" },
          { validator: validatePriceMax, trigger: "change" }
        ]
      },
      pickerOptions: {
        // 日期不能选当日及以后
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e7;
        }
      }
    };
  },
  mounted() {
    this._selectBaseShopPageList(); // 获取门店
    this._getGoodsClassifyTreeList(); // 获取商品分类
  },
  methods: {
    // 权限配置
    setRole(key) {
      return u.selectTitle(this.power, key);
    },
    // 获取门店
    _selectBaseShopPageList() {
      selectBaseShopPageList({
        businessId: this.merchantId,
        type: 3
      }).then(res => {
        let isStore = {
          id: this.merchantId,
          name: this.linkName
        };
        this.storeArr = res.data.list;
        if (this.isShop == "0") {
          this.storeArr.unshift(isStore);
          this.ruleForm.shopId = isStore.id;
        }
      });
    },

    // 获取商品分类
    _getGoodsClassifyTreeList() {
      getGoodsClassifyTreeList().then(res => {
        let data = {
          value: "",
          label: "全部"
        };
        res.data.unshift(data);
        this.options = res.data;
      });
    },

    // 提交搜索
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.pageData.currentPage = 1;
          this._listGoodsProfit(
            this.pageData.pageSize,1
          );
        } else {
          return false;
        }
      });
    },

    // 根据条件获取商品毛利统计
    _listGoodsProfit(pageSize, pageNum) {
      let postPrimaryClassifyId = this.ruleForm.primaryClassifyId[this.ruleForm.primaryClassifyId.length-1] || '';
      let data = {
        endDate: this.ruleForm.date,
        shopId: this.ruleForm.shopId,
        primaryClassifyId: postPrimaryClassifyId,
        startProfit: this.ruleForm.startProfit,
        endProfit: this.ruleForm.endProfit,
        pageSize: pageSize,
        pageNum: pageNum
      };
      this.exportData = JSON.parse(JSON.stringify(data));
      listGoodsProfit(data).then(res => {
        this.tableData = res.data.list;
        this.pageData.totalItems = res.data.pageTotal;
      });
    },

    // 导出
    handleOutput() {
      if (this.tableData.length === 0) {
        this.$message.error("数据为空不能导出");
      } else {
        delete this.exportData.pageSize;
        delete this.exportData.pageNum;
        goodsProfitExport(this.exportData).then(res => {
          let fileName = "商品毛利统计表.xlsx";
          fileDownload(res, fileName);
        });
      }
    }
  }
};
</script>

<style lang="less" scoped>
</style>
